package com.xiaoxiang.file.controller;

import com.aliyun.oss.OSS;
import com.xiaoxiang.common.exception.CommonException;
import com.xiaoxiang.common.result.HttpResult;
import com.xiaoxiang.common.result.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.URL;
import java.util.Date;

/**
 * @author: haha
 * @date: 2022/3/14 18:56
 */
@Controller
public class FileController {

    @Value("${file.bucketName}")
    private String bucketName;

    @Value("${file.expire}")
    private Long expire;

    @Value("${file.basePath}")
    private String basePath;

    @Resource
    private OSS ossClient;

    @GetMapping("/static/{filename}")
    public String accessFile(@PathVariable String filename) {
        Date expiration = new Date(new Date().getTime() + expire);
        URL url = ossClient.generatePresignedUrl(bucketName, filename, expiration);
        return "redirect:" + url;
    }

    @PostMapping(value = "/upload")
    @ResponseBody
    public HttpResult uploadFile(MultipartFile file) {
        String filename = file.getOriginalFilename();
        try {
            ossClient.putObject(bucketName, filename, file.getInputStream());
        } catch (Exception e) {
            throw new CommonException(ResultCodeEnum.FILE_UPLOAD_EXCEPTION, e.getMessage());
        }
        return HttpResult.success(basePath + filename);
    }
}
